import Router from '@koa/router'
import { z } from 'zod'
import { prisma } from '../../app'
import { createError } from '../../middleware/errorHandler'

const router = new Router()

// 验证 schema
const getUsersQuerySchema = z.object({
    page: z.string().optional().transform(val => val ? parseInt(val) : 1),
    limit: z.string().optional().transform(val => val ? parseInt(val) : 10),
    search: z.string().optional()
})

const getUserByIdSchema = z.object({
    id: z.string().min(1, 'User ID is required')
})

const updateUserSchema = z.object({
    nickname: z.string().optional(),
    avatar: z.string().url().optional(),
    bio: z.string().optional(),
    phone: z.string().optional()
})

// 获取用户列表 (Demo 接口)
router.get('/', async (ctx) => {
    try {
        const query = getUsersQuerySchema.parse(ctx.query)
        const { page, limit, search } = query

        const skip = (page - 1) * limit

        // 构建查询条件
        const where = search
            ? {
                OR: [
                    { username: { contains: search } },
                    { nickname: { contains: search } },
                    { email: { contains: search } }
                ]
            }
            : {}

        // 获取用户总数
        const total = await prisma.user.count({ where })

        // 获取用户列表
        const users = await prisma.user.findMany({
            where,
            skip,
            take: limit,
            select: {
                id: true,
                email: true,
                username: true,
                nickname: true,
                avatar: true,
                bio: true,
                createdAt: true,
                updatedAt: true,
                _count: {
                    select: {
                        posts: true,
                        comments: true
                    }
                }
            },
            orderBy: {
                createdAt: 'desc'
            }
        })

        ctx.body = {
            success: true,
            message: 'Users retrieved successfully',
            data: {
                users,
                pagination: {
                    page,
                    limit,
                    total,
                    totalPages: Math.ceil(total / limit),
                    hasNext: page * limit < total,
                    hasPrev: page > 1
                }
            }
        }
    } catch (error) {
        throw error
    }
})

// 根据ID获取用户详情 (Demo 接口)
router.get('/:id', async (ctx) => {
    try {
        const { id } = getUserByIdSchema.parse(ctx.params)

        const user = await prisma.user.findUnique({
            where: { id },
            select: {
                id: true,
                email: true,
                username: true,
                nickname: true,
                avatar: true,
                bio: true,
                phone: true,
                createdAt: true,
                updatedAt: true,
                posts: {
                    select: {
                        id: true,
                        title: true,
                        summary: true,
                        status: true,
                        views: true,
                        likes: true,
                        createdAt: true
                    },
                    orderBy: {
                        createdAt: 'desc'
                    },
                    take: 10
                },
                _count: {
                    select: {
                        posts: true,
                        comments: true
                    }
                }
            }
        })

        if (!user) {
            throw createError.notFound('User not found')
        }

        ctx.body = {
            success: true,
            message: 'User retrieved successfully',
            data: user
        }
    } catch (error) {
        throw error
    }
})

// 获取当前用户信息（需要认证）
router.get('/profile', async (ctx) => {
    try {
        if (!ctx.user) {
            throw createError.unauthorized('User not authenticated')
        }

        const user = await prisma.user.findUnique({
            where: { id: ctx.user.userId },
            select: {
                id: true,
                email: true,
                username: true,
                nickname: true,
                avatar: true,
                bio: true,
                phone: true,
                createdAt: true,
                updatedAt: true,
                _count: {
                    select: {
                        posts: true,
                        comments: true
                    }
                }
            }
        })

        if (!user) {
            throw createError.notFound('User not found')
        }

        ctx.body = {
            success: true,
            message: 'Profile retrieved successfully',
            data: user
        }
    } catch (error) {
        throw error
    }
})

// 更新用户信息（需要认证）
router.put('/profile', async (ctx) => {
    try {
        if (!ctx.user) {
            throw createError.unauthorized('User not authenticated')
        }

        const updateData = updateUserSchema.parse(ctx.request.body)

        const user = await prisma.user.update({
            where: { id: ctx.user.userId },
            data: updateData,
            select: {
                id: true,
                email: true,
                username: true,
                nickname: true,
                avatar: true,
                bio: true,
                phone: true,
                updatedAt: true
            }
        })

        ctx.body = {
            success: true,
            message: 'Profile updated successfully',
            data: user
        }
    } catch (error) {
        throw error
    }
})

// 获取用户统计信息 (Demo 接口)
router.get('/:id/stats', async (ctx) => {
    try {
        const { id } = getUserByIdSchema.parse(ctx.params)

        const user = await prisma.user.findUnique({
            where: { id },
            select: {
                id: true,
                username: true,
                nickname: true
            }
        })

        if (!user) {
            throw createError.notFound('User not found')
        }

        const [postsCount, commentsCount, totalViews, totalLikes] = await Promise.all([
            prisma.post.count({ where: { authorId: id } }),
            prisma.comment.count({ where: { authorId: id } }),
            prisma.post.aggregate({
                where: { authorId: id },
                _sum: { views: true }
            }),
            prisma.post.aggregate({
                where: { authorId: id },
                _sum: { likes: true }
            })
        ])

        ctx.body = {
            success: true,
            message: 'User stats retrieved successfully',
            data: {
                user: {
                    id: user.id,
                    username: user.username,
                    nickname: user.nickname
                },
                stats: {
                    postsCount,
                    commentsCount,
                    totalViews: totalViews._sum.views || 0,
                    totalLikes: totalLikes._sum.likes || 0
                }
            }
        }
    } catch (error) {
        throw error
    }
})

export default router
